import pickle
import base64
from django_redis import get_redis_connection

def merge_cookie_redis_cart(request,user,response):
    """
    :param request: 为了去获取cookie中的数据
    :param user:  为了去获取redis中的数据
    :param response:  为了合并之后可以清空,cookie中的数据
    :return:
    """
    #1,获取cookie中的数据
    cookie_cart = request.COOKIES.get("cart")

    #2,判断cookie是否存在
    if not cookie_cart:
        return response

    try:
        #3,将cookie数据,转换成字典
        cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

        #4,获取redis的数据
        redis_conn = get_redis_connection("cart")
        redis_cart = redis_conn.hgetall("cart_%s"%user.id)
        redis_cart_selcted_list = []

        #5,合并cookie字典数据,到redis中
        for sku_id,count_selected in cookie_cart_dict.items():
            redis_cart[sku_id] = count_selected["count"]
            if count_selected["selected"]:
                redis_cart_selcted_list.append(sku_id)

        #6,设置数据到redis数据库
        redis_conn.hmset("cart_%s"%user.id,redis_cart)
        redis_conn.sadd("cart_selected_%s"%user.id,*redis_cart_selcted_list)

        #7,清除cookie中的数据
        response.delete_cookie("cart")
    except Exception as e:
        pass

    #8,返回
    return response
